package com.testing.sunnyclient.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Classname SunnyAsyncConfiguration
 * @Description 类型说明
 * @Date 2023/5/19 20:13
 * @Created by 特斯汀Roy
 */
@Configuration
@EnableAsync
public class SunnyClientAsyncConfiguration {
    //编写一个自定义的线程池
    @Bean
    @Primary
    public TaskExecutor autoTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(50);
        executor.setMaxPoolSize(200);
        executor.setQueueCapacity(200);

        //获取Ip信息拼接到执行线程中
        String hostAddress = "【客户端地址：";
        //获取所有的ipv4的IP地址
        List<String> ipList = new ArrayList<>();
        try {
            //获取所有网卡
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            NetworkInterface networkInterface;
            Enumeration<InetAddress> inetAddresses;
            InetAddress inetAddress;
            String ip;
            //遍历获取到的所有的网卡
            while (networkInterfaces.hasMoreElements()) {
                //获取下一个网卡元素
                networkInterface = networkInterfaces.nextElement();
                //获取ip地址
                inetAddresses = networkInterface.getInetAddresses();
                //ip地址也可能有多个
                while (inetAddresses.hasMoreElements()) {
                    inetAddress = inetAddresses.nextElement();
                    //只获取ipv4的地址
                    if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
                        //最终得到ip信息
                        ip = inetAddress.getHostAddress();
                        ipList.add(ip);
                    }
                }
            }
            //将列表拼接到执行信息中
            hostAddress += ipList;
        } catch (SocketException e) {
            e.printStackTrace();
        }

        executor.setThreadNamePrefix(hostAddress + "】自动化测试执行线程-");
        //设置拒绝策略为拒绝的时候谁调用谁负责执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //等待所有线程结束之后才关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }


}
